package org.example.commond.handler.room;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.example.commond.AbstractCmdHandler;
import org.example.commond.CommandManager;
import org.example.component.UserInfo;
import org.example.config.Im;
import org.example.enums.CommandEnum;
import org.example.packets.bean.Group;
import org.example.packets.bean.User;
import org.example.packets.handler.message.ChatReqBody;
import org.example.packets.handler.message.ChatRespBody;
import org.example.packets.handler.room.AnnouncementReqBody;
import org.example.packets.handler.system.RespBody;
import org.example.util.JsonUtil;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import java.util.Date;

public class AnnouncementReqHandler extends AbstractCmdHandler {

    @Override
    public CommandEnum command() {
        return CommandEnum.COMMAND_GROUP_ANNOUNCEMENT_REQ;
    }

    @Override
    public WsResponse handler(Packet packet, ChannelContext channelContext) {

        AnnouncementReqBody body = JsonUtil.format(packet,AnnouncementReqBody.class);

        // 获取当前用户
        User user = UserInfo.user();

        // 保存群组公告编号到群组信息中
        String announcementId = ObjectUtil.defaultIfNull(body.get_id(), IdUtil.getSnowflake().nextIdStr());
        Group groupInfo = groupService.getGroupInfo(body.getRoomId());
        groupInfo.setAnnouncementId(announcementId);
        groupService.updateById(groupInfo);

        // 发布群组公告消息到群组(作为普通对话信息)
        AbstractCmdHandler command = CommandManager.getCommand(CommandEnum.COMMAND_CHAT_REQ);
        ChatReqBody chatReqBody = new ChatReqBody();
        chatReqBody.set_id(announcementId);
        chatReqBody.setContent("[群公告]" + System.lineSeparator() + body.getContent());
        chatReqBody.setRoomId(body.getRoomId());

        WsRequest wsRequest = WsRequest.fromText(JSON.toJSONString(chatReqBody, SerializerFeature.DisableCircularReferenceDetect), Im.CHARSET);
        command.handler(wsRequest, channelContext);

        ChatRespBody chatRespBody = new ChatRespBody();
        chatRespBody.setId(announcementId);
        chatRespBody.setContent(body.getContent());
        chatRespBody.setRoomId(body.getRoomId());
        chatRespBody.setSenderId(user.getId());
        chatRespBody.setUsername(user.getUsername());
        chatRespBody.setAvatar(user.getAvatar());
        Date date = new Date();
        chatRespBody.setDate(DateUtil.formatDate(date));
        chatRespBody.setTimestamp(DateUtil.formatTime(date));
        String success = RespBody.success(CommandEnum.COMMAND_GROUP_ANNOUNCEMENT_RESP, chatRespBody);
        WsResponse response = WsResponse.fromText(success, Im.CHARSET);
        Im.sendToGroup(body.getRoomId(), response);

        return null;
    }
}
